<template>
	<view class="all">
		<view class="container">
			<!-- 标题 -->
			<view class="title">Pollen Dispersal Predict History</view>

			<!-- 编辑和返回按钮 -->
			<view class="buts">
				<view class="edit-button" @click="toggleEdit">
					{{ isEditing ? 'Edit Finish' : 'Edit' }}
				</view>
				<view class="back-button" @click="navigatorback">
					back
				</view>
			</view>

			<!-- 操作按钮 -->
			<view class="action-buttons" v-if="isEditing">
				<view class="popup-button" @click="cancelEdit">Cancel</view>
				<view class="popup-button" @click="toggleSelectAll">{{ allSelected ? 'Deselect All' : 'Select All' }}
				</view>
				<view class="popup-button" @click="exportSelected">Export</view>
				<view class="popup-button" @click="deleteSelected">Delete</view>
			</view>

			<!-- 数据加载状态 -->
			<div v-if="isLoading" class="loading-indicator">
				The history is being obtained...
			</div>

			<!-- 显示结果 -->
			<view class="content" v-for="(response, index) in sortedResponses" :key="index">
				<text class="time-title">{{ response.uploadTime }}</text>
				<checkbox-group @change="(event) => handleCheckboxChange(event, index)">
					<view v-for="(result, resIndex) in response.allResult" :key="resIndex" class="result-item">
						<!-- 编辑模式下显示checkbox -->
						<checkbox :value="result.id" :checked="result.selected" v-if="isEditing"></checkbox>

						<!-- 图片展示 -->
						<img :src="`data:image/jpeg;base64,${result.base64Image}`" class="result-image" />

						<!-- 使用resultTable组件显示结实率和可信度 -->
						<view class="levels">
							<result-table :result="result.result" :credibility="result.credibility" :height="'160rpx'"
								class="result-table" />
						</view>

						<!-- 备注编辑框 -->
						<view class="beizhu">
							<uni-easyinput type="textarea" v-model="result.remark" @blur="handleBlur(result)"
								@focus="storeOriginalRemark(result)" placeholder="Edit" />
						</view>
					</view>
				</checkbox-group>
			</view>

		</view>
	</view>
</template>
<script setup>
import {
	ref,
	computed,
	onMounted
} from 'vue';
import resultTable from '../../components/resultTable.vue';
import {
	onLoad,
	onShow
} from "@dcloudio/uni-app"
const userId = ref(null);
const token = ref(null);
const responses = ref([]);
const isEditing = ref(false);
const selectedIds = ref([]);
const allSelected = ref(false);
const isLoading = ref(false);
const heights = ref(1000);
// 用于存储原始备注  
const originalRemarks = ref({});
// 获取用户ID  
const getUserId = () => {
	return new Promise((resolve, reject) => {
		uni.getStorage({
			key: 'user-data',
			success: (res) => {
				userId.value = res.data.userId;
				console.log('获取到的用户ID:', userId.value);
				resolve();
			},
			fail: reject,
		});
	});
};
const navigatorback = () => {
	uni.navigateTo({
		url: '/pages/user/index',
	});
};

// 获取令牌  
const getToken = () => {
	return new Promise((resolve, reject) => {
		uni.getStorage({
			key: 'user-data',
			success: (res) => {
				token.value = res.data.token;
				console.log('获取到的令牌:', token.value);
				resolve();
			},
			fail: reject,
		});
	});
};

// 调用API获取数据  
const fetchResponses = () => {
	isLoading.value = true;
	uni.request({
		url: `https://maize.ltd/yumi/find/sanfenPredict/${userId.value}`,
		method: 'POST',
		header: {
			'token': token.value,
		},
		success: (response) => {
			isLoading.value = false
			console.log('获取到的数据:', response.data);
			responses.value = response.data.data || []; // 更新数据  
		},
		fail: (error) => console.error('Error fetching data:', error),
		finally: () => isLoading.value = false, // 不管成功与否都设置加载状态为false  
	});
};

onMounted(() => {
	// 获取用户ID和令牌  
	Promise.all([getUserId(), getToken()])
		.then(() => fetchResponses())
		.catch(err => console.error('获取 ID 或令牌失败:', err));
});


// 处理输入框失去焦点事件  
const handleBlur = (result) => {
	if (originalRemarks.value[result.id] !== result.remark) {
		updateRemark(result.id, result.remark); // 仅当内容发生变化时更新备注  
	}
};

// 存储原始备注   
const storeOriginalRemark = (result) => {
	originalRemarks.value[result.id] = result.remark; // 保存原始内容  
	result.currentRemark = result.remark; // 初始化当前内容  
};
// 更新备注  
const updateRemark = (id, remark) => {
	console.log('Updating remark', id);
	uni.request({
		url: `https://maize.ltd/yumi/sanfenPredict/remark`,
		method: 'PUT',
		data: {
			id,
			remark
		},
		header: {
			token: token.value
		},
		success: (res) => {
			if (res.data.code === 200) {
				uni.showToast({
					title: 'updated'
				})
			} else { }
		},
		fail: (err) => {
			console.error('Failed to modify the remark request:', err);
			uni.showModal({
				title: 'Tip',
				content: 'Network error',
				showCancel: false,
				confirmText: 'OK'
			});
		}
	});
};

// 根据上传时间排序  
const sortedResponses = computed(() => {
	return Array.isArray(responses.value) ?
		responses.value.sort((a, b) => new Date(b.uploadTime) - new Date(a.uploadTime)) : [];
});

// 获取结实率和可信度数据  
const topThreeLevels = (result) => {
	const levels = [];
	for (let i = 0; i <= 5; i++) {
		const valueStr = result[`lu${i}`];
		if (valueStr.includes('E')) {
			valueStr = "0.0000000000001";
		}
		let value = parseFloat(valueStr) || 0; // 直接转换为数字或设为0  
		levels.push({
			index: i,
			value
		});
	}
	return levels.sort((a, b) => b.value - a.value).slice(0, 3).map(({
		index,
		value
	}) => ({
		level: `lu ${index}`,
		percentage: (value * 100).toFixed(2) + '%'
	}));
};

// 切换编辑状态  
const toggleEdit = () => {
	isEditing.value = !isEditing.value;
	if (!isEditing.value) resetSelections();
};

const cancelEdit = () => {
	isEditing.value = !isEditing.value;
	if (!isEditing.value) {
		// 如果退出编辑模式，将所有结果重置为未选中状态  
		responses.value.forEach(response => {
			response.allResult.forEach(result => {
				result.selected = false;
			});
		});
		selectedIds.value = []; // 清空选中的 ID 数组  
	}
}

// 重置选中状态  
const resetSelections = () => {
	responses.value.forEach(response => {
		response.allResult.forEach(result => {
			result.selected = false;
		});
	});
	selectedIds.value = [];
};

// 处理选中项变化  
const handleCheckboxChange = (event, index) => {

	if (event.detail.value.length) {

		selectedIds.value.push(index)
	} else {
		selectedIds.value = selectedIds.value.filter(id => id !== index)
	}

	console.log("选中的 ID:", selectedIds.value);
};

// 切换全选状态  
const toggleSelectAll = () => {
	allSelected.value = !allSelected.value;
	responses.value.forEach(response => {
		response.allResult.forEach(result => {
			result.selected = allSelected.value;
		});
	});
	selectedIds.value = allSelected.value ?
		responses.value.flatMap(response => response.allResult.map(result => result.id)) : [];
};

// 删除选中项  
const deleteSelected = () => {
	if (selectedIds.value.length === 0) return
	uni.request({
		url: `https://maize.ltd/yumi/sanfenPredict/delete?ids=${selectedIds.value}`,
		method: 'DELETE',
		header: {
			token: token.value
		},
		success: (response) => {
			console.log('Deleted data:', response.data);
			responses.value = responses.value.map(response => ({
				...response,
				allResult: response.allResult.filter(result => !selectedIds.value.includes(
					result.id))
			})).filter(response => response.allResult.length > 0);
			resetSelections();
			uni.showModal({
				title: 'Tip',
				content: 'Delete successful',
				showCancel: false,
				confirmText: 'OK'
			});

		},
		fail: (error) => {
			console.error('Error fetching data:', error);

			resetSelections()
		}
	});
};

// 导出功能  
const export1 = () => {
	console.log('启动导出');
	let yOffset = 20;
	const selectedResults = responses.value.flatMap(response => response.allResult.filter(result => selectedIds
		.value.includes(result.id)));

	if (selectedResults.length === 0) {
		uni.showModal({
			title: 'Tip',
			content: 'select first',
			showCancel: false,
			confirmText: 'OK'
		});
		return;
	}

	heights.value = calculateCanvasHeight(selectedResults); // 计算 Canvas 高度  
	const ctx = uni.createCanvasContext('myCanvas', this, {
		willReadFrequently: true
	});

	yOffset = drawCanvasContent(ctx, selectedResults, yOffset);
	heights.value = yOffset; // 更新 heights 的值  

	// 导出 Canvas 为图片  
	ctx.draw(true, () => {
		uni.canvasToTempFilePath({
			x: 0,
			y: 0,
			width: 250,
			height: heights.value,
			canvasId: 'myCanvas',
			success: (res) => {
				console.log('导出的:', res);
				saveImageToLocal(res.tempFilePath);
			},
			fail: (err) => console.error('导出失败:', err),
		});
	});
};

// 计算 Canvas 高度  
const calculateCanvasHeight = (selectedResults) => {
	let totalHeight = 0;
	const uniqueUploadTimes = new Set();

	selectedResults.forEach(result => {
		const response = responses.value.find(r => r.allResult.some(res => res.id === result.id));
		if (response) {
			if (!uniqueUploadTimes.has(response.uploadTime)) {
				uniqueUploadTimes.add(response.uploadTime);
				totalHeight += 5 + 30 + 10; // 间隔和图片高度  
			}
			const levels = topThreeLevels(result.result);
			totalHeight += (levels.length * 20) + 10 + 30; // 结实率高度和备注高度  
		}
	});

	return totalHeight;
};

// 绘制 Canvas 内容  
const drawCanvasContent = (ctx, selectedResults, yOffset) => {
	const uniqueUploadTimes = new Set();

	selectedResults.forEach(result => {
		const response = responses.value.find(r => r.allResult.some(res => res.id === result.id));
		if (response && !uniqueUploadTimes.has(response.uploadTime)) {
			uniqueUploadTimes.add(response.uploadTime);
			ctx.fillText(response.uploadTime, 10, yOffset);
			yOffset += 5;

			response.allResult.forEach(result => {
				if (selectedIds.value.includes(result.id)) {
					ctx.drawImage(`data:image/jpeg;base64,${result.base64Image}`, 10, yOffset, 30,
						30);
					yOffset += 40;

					ctx.fillText(
						`Powder Dispensing?: ${result.result === 'san1' ? 'Yes' : result.result === 'san0' ? 'No' : 'N/A'}     credibility: ${(result.credibility * 100).toFixed(2)}%`,
						10, yOffset);
					yOffset += 20;


					ctx.fillText(`备注: ${result.remark || 'null'}`, 10, yOffset);
					yOffset += 30;
				}
			});
			yOffset += 10; // 每个响应的间隔  
		}
	});

	return yOffset;
};

// 保存图片到本地相册  
const saveImageToLocal = (tempFilePath) => {
	uni.saveImageToPhotosAlbum({
		filePath: tempFilePath,
		success: () =>
			uni.showModal({
				title: 'Tip',
				content: 'Save successful',
				showCancel: false,
				confirmText: 'OK'
			}),
		fail: (err) => {
			console.error('Save failed:', err);
			uni.showModal({
				title: 'Tip',
				content: 'Save failed',
				showCancel: false,
				confirmText: 'OK'
			});
		}
	});
};

// 导出选中的项  
const exportSelected = () => {
	export1();
};
</script>



<style lang="less" scoped>
.container {
	padding-top: 140rpx;
	min-height: 100vh;
	position: relative;
	background-color: #e3f2e3;
	overflow: hidden;

	.title {
		text-align: center;
		font-size: 40rpx;
		font-weight: bold;
		color: #4CAF50;
		margin-bottom: 50rpx;
	}

	.buts {
		display: flex;
		justify-content: space-around;
	}

	.edit-button,
	.back-button {
		color: white;
		background-color: #4CAF50;
		padding: 10rpx;
		border-radius: 5rpx;
		text-align: center;
		cursor: pointer;
		width: 140rpx;
		margin-bottom: 80rpx;
	}

	.action-buttons {
		margin-bottom: 105rpx;
		margin-left: 20rpx;
		display: flex;

		.popup-button {
			color: #4CAF50;
			cursor: pointer;
			margin-right: 30rpx;
		}
	}

	.content {
		margin-bottom: 20rpx;
		margin-left: 20rpx;
		width: auto;

		.time-title {
			font-size: 28rpx;
			color: #666;
			margin-bottom: 10rpx;
		}

		.result-item {
			background-color: #ffffff;
			border: 1rpx solid #ddd;
			border-radius: 8rpx;
			padding: 10rpx;
			box-shadow: 0 2rpx 5rpx rgba(0, 0, 0, 0.1);
			margin-bottom: 15rpx;
			display: flex;
			align-items: center;
			width: 95%;
			margin-right: 10rpx;

			.result-image {
				width: 160rpx;
				height: 160rpx;
				object-fit: cover;
				border-radius: 8rpx;
				margin-right: 10rpx;
			}

			.levels {
				flex-grow: 1;
				margin-right: 10rpx;
				// 样式由组件内部提供，高度通过组件props控制
			}

			.beizhu {
				width: 250rpx;
			}
		}
	}
}
</style>